package gbench.appdemo.mall.appitf.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import gbench.common.fs.FileSystem;
import gbench.common.tree.LittleTree.IRecord;
import static gbench.common.tree.LittleTree.IRecord.*;

@RestController
@RequestMapping("/file")
public class MultipartFileController {

    /**
     * 文件上传
     * @param file 文件对象
     * @return 上传结果，ossurl中函数含有上传的文件的可访问的url
     */
    @PostMapping("upload")
    public IRecord ossUpload(@RequestParam("myfile") final MultipartFile file) {
        return this.save2cloud(file);
    }

    /**
     * 处理文件上传
     * 
     * @param file MultipartFile 多媒体文件类型
     * @return 返回的结果是一段json数据
     */
    public IRecord save2cloud(final MultipartFile file) {
        final var rec = REC();
        String home = FileSystem.path("upload", this.getClass());// 上传文件保存位置
        File homeDir = new File(home);// 文件路径
        if (!homeDir.exists())
            homeDir.mkdirs();
        try {
            Path path = Paths.get(homeDir.getAbsolutePath() + "/" + file.getOriginalFilename());
            System.out.println("上传文件保存至:" + path + "!");
            rec.add("cachedpath", path.toString());
            Files.write(path, file.getBytes());
            String ossurl = path.toString();
            rec.add("ossurl", ossurl);
        } catch (IOException e) {
            rec.add("error", e.getMessage());
            e.printStackTrace();
        }
        
        rec.add("msg", "上传成功");
        return rec;
    }

}
